import React from 'react';
import { observer, inject } from 'mobx-react';
import { Button, Icon, Popover, ActionSheet, List, InputItem } from 'weaver-mobile';
import QRCode from './QRCode';

const jQuery = window.jQuery;

@inject('portalLoginStore')
@observer
class Login extends React.Component {
  constructor(props) {
    super(props);
    this.getLoginForm = this.getLoginForm.bind(this);
    this.onLoginTypeChange = this.onLoginTypeChange.bind(this);
    this.getDynamicPassword = this.getDynamicPassword.bind(this);
    this.onLanguageChange = this.onLanguageChange.bind(this);
    this.onLanguagesVisibleChange = this.onLanguagesVisibleChange.bind(this);
    this.onRememberChange = this.onRememberChange.bind(this);
    this.onValidateCodeChange = this.onValidateCodeChange.bind(this);
    this.onForgot = this.onForgot.bind(this);
    this.onLogin = this.onLogin.bind(this);
    this.onServerChange = this.onServerChange.bind(this); 
	this.initHeight = this.initHeight.bind(this);
  }		
	
  componentWillMount() {
    const { portalLoginStore: store } = this.props;
    store.getLanguages();
  }
  
  componentDidMount(){
	  const innerHeight = window.innerHeight;
	  window.addEventListener('resize', () => {
		const newInnerHeight = window.innerHeight;
		if (innerHeight > newInnerHeight) {
			// 键盘弹出事件处理
			//alert("android 键盘弹窗事件");
			setTimeout(function () {
				jQuery(".portal-login-content").height(innerHeight - 120);
			},200)
		} else {
			// 键盘收起事件处理
			//alert("android 键盘收起事件处理");
			setTimeout(function () {
				jQuery(".portal-login-content").height(innerHeight - 120);
			},200)
		}
	});
  }
  componentWillUnmount(){
	  
  }
  
  componentDidUpdate() {
    const { client } = this.props;
    if (client == 'pc') {
      const _this = this;
      jQuery('.portal-login-form-input input')
        .unbind()
        .keydown(function(e) {
          e = e || window.event;
          const key = e.keyCode || e.which || e.charCode;
          if (key == 13) {
            const inputs = jQuery('.portal-login-form-input input');
            const idx = inputs.index(this);
            const nxtIdx = idx + 1;
            const nxtInput = jQuery('.portal-login-form-input input:eq(' + nxtIdx + ')');
            if (nxtInput.length > 0) {
              nxtInput.focus();
            } else {
              _this.onLogin();
            }
          }
        });
    }
  }

  render() {
    const { portalLoginStore: store, client } = this.props;
    const {
      loading,
      logining,
      language = {},
      languages = [],
      languagesVisible,
      data = {},
      labels = {},
      remember,
      remembered = {},
      loginForm = {},
      dynamicPasswordTime = 0,
      validateCode,
      loginType,
	  inputlogintype
    } = store;
    const { logoconfig = {}, copyrightconfig = {}, qrcodeconfig = {} } = data;
    const { showQrcode, defaultQrcode, onlyQrcode } = qrcodeconfig;
    const { loginFormItems = [], loginFormHiddenItems = [], loginSetting = {} } = loginForm;
    const { hasMultiLang, needforgotpassword, validateCodeKey } = loginSetting;
    const validateCodeSrc = validateCode + '&validateCodeKey=' + validateCodeKey;

    if (loading) {
      return null;
    }

    return (
      <div className="portal-login">
        <style type="text/css">{store.style}</style>
        <div className="portal-login-content" style={{ minHeight: document.body.clientHeight - 120 }}>
          <div className="portal-login-top">
            {hasMultiLang && languages.length > 1 && (
              <Popover
                mask={true}
                visible={languagesVisible}
                onVisibleChange={this.onLanguagesVisibleChange}
                overlay={languages.map(item => {
                  return <Popover.Item key={item.id}>{item.language}</Popover.Item>;
                })}
                overlayClassName="portal-login-languages"
                onSelect={this.onLanguageChange}
              >
                <div className="portal-login-language" style={{ right: client == 'pc' && showQrcode && !onlyQrcode ? 50 : 20 }}>
                  <span className="portal-login-language-text">{language.language}</span>
                </div>
              </Popover>
            )}
            {client == 'pc' && showQrcode && !onlyQrcode && (
              <div className="portal-login-type">
                {loginType == 'form' && (
                  <span className="portal-login-type-text" title={labels.label12} onClick={() => this.onLoginTypeChange('qrcode')}>
                    <Icon type="sweep" size="xs" />
                  </span>
                )}
                {loginType == 'qrcode' && (
                  <span className="portal-login-type-text" title={labels.label13} onClick={() => this.onLoginTypeChange('form')}>
                    <Icon type="forward-mail" size="xs" />
                  </span>
                )}
              </div>
            )}
          </div>
          <div className="portal-login-logo">
            {logoconfig.logoImg && <div className="portal-login-logo-img"><img src={logoconfig.logoImg} alt="" /></div>}
            {logoconfig.logoText && <div className="portal-login-logo-text">
              <div className="portal-login-text-1">欢迎使用,</div>
              <div className="portal-login-text-2">政务通</div>
            </div>}
          </div>
          {(client == 'mobile' || loginType == 'form') && (
            <div className="portal-login-input">
              <div className="portal-login-form">
                {loginFormItems.map((item, index) => {
                  if (item.atype == 'account') {
                    return (
                        <div key={index} className="portal-login-form-item">
                          <div className="portal-login-form-label">
                            账号
                          </div>
                          <div className="portal-login-form-control">
                            <List>
                              <InputItem
                                  type={item.type}
                                  id={item.id}
                                  name={item.name}
                                  defaultValue={remembered[item.atype]}
                                  placeholder="请输入账号"
                                  className="portal-login-form-input"
                                  onBlur={value => { window.scroll(0, 0); this.getLoginForm(value);this.initHeight() }}
                              />
                            </List>
                            {client == 'mobile' && <input type="text" style={{ position: 'absolute', left: -99999 }} />}
                          </div>
                        </div>
                    );
                  } else if (item.atype == 'dynamicPassword') {
                    return (
                      <div key={index} className="portal-login-form-item">
                         <div className="portal-login-form-label">
                            短信
                          </div>
                          <div className="portal-login-form-control">
                            <div className="portal-login-dynamic">
                              {dynamicPasswordTime > 0 ? (
                                  <span className="portal-login-dynamic-text" style={{ color: '#ccc' }}>
                                {labels.label11}({dynamicPasswordTime}s)
                              </span>
                              ) : (
                                  <span className="portal-login-dynamic-text" onClick={this.getDynamicPassword}>
                                {labels.label10}
                              </span>
                              )}
                            </div>
                            <List>
								<InputItem 
									type={item.type} 
									id={item.id} 
									name={item.name} 
									placeholder="请输入短信验证码" 
									className="portal-login-form-input" 
									onBlur={() => {window.scroll(0, 0);this.initHeight()}}
								/>
							</List>
                          </div>
                        </div>
                    );
                  } else if (item.atype == 'validatecode') {
                    return (
                      <div key={index} className="portal-login-form-item">
                        <div className="portal-login-form-label">
                          <Icon type="verification-code" />
                        </div>
                        <div className="portal-login-form-control">
                          <img src={validateCodeSrc} alt="" className="portal-login-validatecode" onClick={this.onValidateCodeChange} />
                          <List><InputItem type={item.type} id={item.id} name={item.name} placeholder={item.label} className="portal-login-form-input" onBlur={() => window.scroll(0, 0)} /></List>
                        </div>
                      </div>
                    );
                  } else {
                    return (
                        <div key={index} className="portal-login-form-item">
                          <div className="portal-login-form-label">
                            密码
                          </div>
                          <div className="portal-login-form-control">
                            <List>
                              <InputItem
                                  type={item.type}
                                  id={item.id}
                                  name={item.name}
                                  defaultValue={remembered[item.atype]}
                                  placeholder="请输入密码"
                                  className="portal-login-form-input"
                                  onBlur={() => {window.scroll(0, 0);this.initHeight()}}
                              />
                            </List>
                          </div>
                        </div>
                    );
                  }
                })}
                {loginFormHiddenItems.map((item, index) => {
                  return <div key={index} style={{ display: 'none' }} dangerouslySetInnerHTML={{ __html: item.html }} />;
                })}
              </div>
              <div className="portal-login-remember">
                <span className="portal-login-remember-text" onClick={this.onRememberChange}>
                  {{ 1: labels.label4, 2: labels.label5, 3: labels.label6 }[remember]}
                </span>
              </div>
              <div className="portal-login-button">
                <Button type="primary" loading={logining} onClick={this.onLogin}>
                  {labels.label3}
                </Button>
                <div className="portal-login-imgbutton">
                  <Button type="primary" loading={logining} onClick={this.onLogin}>
                    <div className="imgbutton-text">{labels.label3}</div>
                  </Button>
                </div>
              </div>
              {needforgotpassword == '1' && (
                <div className="portal-login-forgot">
                  <span className="portal-login-forgot-text" onClick={this.onForgot}>
                    {labels.label1}
                  </span>
                </div>
              )}
            </div>
          )}
          {client == 'pc' && loginType == 'qrcode' && <QRCode />}
        </div>
        <div className="portal-login-bottom" style={{ height: 120 }}>
          <div className="portal-login-bottom-content">
            <div className="portal-login-server">
              <span className="portal-login-server-text" onClick={this.onServerChange}>
                {labels.label2}
              </span>
            </div>
			<div className="portal-login-types" style={{height:'40px',lineHeight:'40px',textAlign:'center'}}>
              {inputlogintype==0&&<span className="portal-login-type-item" onClick={()=>this.inputloginTypeChange(1)}>
                短信登录
              </span>}
              {inputlogintype==1&&<span className="portal-login-type-item" onClick={()=>this.inputloginTypeChange(0)}>
                账号密码登录
              </span>}
            </div>
            <div className="portal-login-copyright">
              <span className="portal-login-copyright-text" dangerouslySetInnerHTML={{ __html: copyrightconfig.fontText }} />
            </div>
          </div>
        </div>
      </div>
    );
  }
	
  inputloginTypeChange=(type)=>{
    const { portalLoginStore: store } = this.props;
    store.setImputLoginType(type);
    this.getLoginForm();

  }
  initHeight(){
	 setTimeout(function () {
		jQuery(".portal-login-content").height(document.body.clientHeight - 120);
	 },200)
  }	
  getLoginForm() {    
    const { portalLoginStore: store } = this.props;
    store.getLoginForm();
  }

  onLoginTypeChange(loginType) {
    const { portalLoginStore: store } = this.props;
    store.onLoginTypeChange(loginType);
  }

  getDynamicPassword() {
    const { portalLoginStore: store } = this.props;
    store.getDynamicPassword();
  }

  onLanguageChange(node = {}) {
    const { portalLoginStore: store } = this.props;
    store.onLanguageChange(node.key);
  }

  onLanguagesVisibleChange(visible) {
    const { portalLoginStore: store } = this.props;
    store.onLanguagesVisibleChange(visible);
  }

  onRememberChange() {
    const { portalLoginStore: store } = this.props;
    const { labels = {} } = store;

    const BUTTONS = [
      {
        content: labels.label4,
        onClick: () => store.onRememberChange(1)
      },
      {
        content: labels.label5,
        onClick: () => store.onRememberChange(2)
      },
      {
        content: labels.label6,
        onClick: () => store.onRememberChange(3)
      },
      {
        content: labels.label8,
        onClick: () => {}
      }
    ];
    ActionSheet.showActionSheetWithOptions({
      options: BUTTONS,
      cancelButtonIndex: BUTTONS.length - 1,
      maskClosable: true
    });
  }

  onValidateCodeChange() {
    const { portalLoginStore: store } = this.props;
    store.onValidateCodeChange();
  }

  onForgot() {
    const { portalLoginStore: store } = this.props;
    store.onForgot();
  }

  onLogin() {
    const { portalLoginStore: store } = this.props;
    store.onLogin();
  }

  onServerChange() {
    const { portalLoginStore: store } = this.props;
    store.onServerChange();
  }
}

export default Login;
